package com.xyhuo.leetcode.january;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 随机链表的复制
 * https://leetcode.cn/problems/copy-list-with-random-pointer/
 *
 * @time 2024/1/17
 */
public class CopyRandomList {

    public Node copyRandomList(Node head) {
        if (null == head) {
            return null;
        }
        Node tmp = head;
        List<Node> copyNodeList = new ArrayList<>();
        while (tmp != null) {
            Node copyNode = new Node(tmp.val);
            if (!copyNodeList.isEmpty()) {
                copyNodeList.get(copyNodeList.size() - 1).next = copyNode;
            }
            copyNodeList.add(copyNode);
            tmp = tmp.next;
        }
        Map<Node, Integer> nodeIndexMap = getNodeIndexMap(head);
        tmp = head;
        int index = 0;
        while (tmp != null) {
            if (tmp.random != null) {
                Integer randomIndex = nodeIndexMap.get(tmp.random);
                copyNodeList.get(index).random = copyNodeList.get(randomIndex);
            }
            index++;
            tmp = tmp.next;
        }
        return copyNodeList.get(0);
    }

    private Map<Node, Integer> getNodeIndexMap(Node head) {
        Node tmp = head;
        Map<Node, Integer> map = new HashMap<>();
        int index = 0;
        while (null != tmp) {
            map.put(tmp, index++);
            tmp = tmp.next;
        }
        return map;
    }

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
}
